	package com.GLM.Viewer.Circle;

	import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
	import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

	import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

	import com.GLM.Constants.Constant;
import com.GLM.Entity.RingEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Image.AvatarUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Party.PartyDetailActivity;
import com.google.gson.Gson;

	public class CircleSendSMSActivity extends Activity {
		private final static int MYCIRCLELIST_LOADING = 111;
		private final static int MYCIRCLELIST_LONDED = 222;

		private String[] itemKeys = new String[] { "msgNum", "fansNum", "circleName" };
		private int[] itemIds = new int[] { R.id.mycirclelistitem_message, R.id.myciclelistitem_fans, R.id.mycirclelistitem_name };

		private int mUserId;
		RingEntity ringEntity;
		private ProgressBar mProgressBar;
		Button btnImageView;
		private ListView mListView;
		private SimpleAdapter mAdapter;
		private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();
		private List<RingEntity> allRings = new ArrayList<RingEntity>();
		private int screenWidth;
		private int screenHeight;
		View mInputFieldMoreLines;
		EditText mInputFieldMoreLinesEditText;
		Animation mAnimIn;
		Animation mAnimOut;
		InputMethodManager imm;
		
		public String photoName;
		private Bitmap mDrawableAvater;
		private String takePhotoPath;
		private String fromalbumPath;
		private boolean takePhoto = false;
		private boolean fromAlbum = false; 
		private final Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Thread thread;
				switch (msg.what) {
				case MYCIRCLELIST_LOADING:
					mProgressBar.setVisibility(View.VISIBLE);
					thread = new Thread(new Runnable() {
						public void run() {
							
							initMyCircleList();
							mAdapter = new SimpleAdapter(CircleSendSMSActivity.this, mItems, R.layout.view_mycircles_listitem, itemKeys, itemIds);
							mHandler.sendEmptyMessage(MYCIRCLELIST_LONDED);
						}
					});
					thread.start();
					break;

				case MYCIRCLELIST_LONDED:
					mProgressBar.setVisibility(View.GONE);
					if(mAdapter != null && mItems.size()>0){
						mListView.setAdapter(mAdapter);
						
						bindItemClickedEvent();
					}else{
						Paint paint = new Paint();
						paint.setTextSize(20);
						paint.setAntiAlias(true);
						String str = getString(R.string.circle_nocircle);
						Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
						Canvas canvas = new Canvas(bitmap);
						canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
						RelativeLayout layout = (RelativeLayout)findViewById(R.id.mycirles_layout1);
						Drawable drawable = new BitmapDrawable(bitmap);
						layout.setBackgroundDrawable(drawable);
					}
					
					break;
				}
			}
		};

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			screenWidth = getWindowManager().getDefaultDisplay().getWidth();
			screenHeight = getWindowManager().getDefaultDisplay().getHeight();
			setContentView(R.layout.view_mycircles_list);
			imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			mProgressBar = (ProgressBar) findViewById(R.id.mycirclelist_progressbar);
			mListView = (ListView) findViewById(R.id.mycirclelist_listview);
			mUserId = UserInfoDAO.getUserInfo(this).getUserId();
			initInputFields();
			initAnimation();
			initRegisterInputFieldButton();
			mHandler.sendEmptyMessage(MYCIRCLELIST_LOADING);
			
		}

		private void initInputFields() {
			mInputFieldMoreLines = findViewById(R.id.inputfield_moreline);
			mInputFieldMoreLines.setVisibility(View.GONE);
			mInputFieldMoreLinesEditText = (EditText) findViewById(R.id.inputfieldmoreline_edittext);
			
		}

		private void initAnimation() {
			mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
			mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
		}
		
		private void initRegisterInputFieldButton() {
			// more line
			btnImageView = (Button)findViewById(R.id.comment_image_button);
			btnImageView.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
					AlertDialog.Builder builder = new AlertDialog.Builder(CircleSendSMSActivity.this);
					builder.setPositiveButton(getString(R.string.avater_album), new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
							intent.addCategory(Intent.CATEGORY_OPENABLE);
							intent.setType("image/*");
							startActivityForResult(Intent.createChooser(intent, "Selete Picture"), Constant.ACTIVITY_REQUESTCODE_ALBUM);
						}
					});
					builder.setNeutralButton(getString(R.string.avater_takepicture), new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE);
						}
					});
					builder.setNegativeButton(getString(R.string.cancel), null);
					builder.setTitle(getString(R.string.newparty_tips_dialog));
					builder.show();
				}
			});
			Button inputMoreLineCancelButton = (Button) findViewById(R.id.inputfieldmoreline_cancelbutton);
			inputMoreLineCancelButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					hideMoreLinesInputField();
				}
			});

			Button inputMoreLineOkButton = (Button) findViewById(R.id.inputfieldmoreline_okbutton);
			inputMoreLineOkButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					String comContext = mInputFieldMoreLinesEditText.getText().toString().trim();
					if(!comContext.equals("")){
						hideMoreLinesInputField();
						try {
							if(takePhoto || fromAlbum)
								uploadFile();
						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						initComment(comContext);
					}
				}
			});
			
		}
		
		private void hideMoreLinesInputField() {
			mInputFieldMoreLinesEditText.setText("");
			mInputFieldMoreLinesEditText.clearFocus();
			mInputFieldMoreLines.startAnimation(mAnimOut);
			mInputFieldMoreLines.setVisibility(View.GONE);
			imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		}
		
		private void showMoreLinesInputField() {
			mInputFieldMoreLines.startAnimation(mAnimIn);
			mInputFieldMoreLines.setVisibility(View.VISIBLE);
			mInputFieldMoreLinesEditText.requestFocus();
			imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		}
		public int initComment(String comContext){
			JSONObject jsonData = new JSONObject();
			JSONResponse jsonResponse = null;
			int status = -1;
			try {
				jsonData.put(Constant.PARAM_USERID_ONE, mUserId);
				jsonData.put("issue", 2);
				jsonData.put("spreadLevel", 0);
				jsonData.put("parent_id", 0);
				jsonData.put("mc_id",0);
				jsonData.put("ring_id", ringEntity.getRing_id());
				jsonData.put("content", comContext);
				jsonData.put("state", 1);
				if(fromAlbum || takePhoto)
					jsonData.put("picture", photoName);
				Log.d("jsonData", jsonData.toString());
				jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_STORECOMMENT, jsonData);

				if (jsonResponse.getStatus() != Status.ERR) {
					JSONObject data = jsonResponse.getData();
					
					status = data.getInt(Constant.RESP_STATUS);
					
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			return status;
		}
		
		private void initMyCircleList() {
			JSONObject jsonData = new JSONObject();
			JSONResponse jsonResponse = null;
			try {
				jsonData.put(Constant.PARAM_USERID, mUserId);
				jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETMYCIRCLELIST, jsonData);

				if (jsonResponse.getStatus() != Status.ERR) {
					JSONObject data = jsonResponse.getData();
					int status = -1;
					status = data.getInt(Constant.RESP_STATUS);
					if (status == Constant.RESP_STATUS_SUCCESS) {
						JSONArray jsonArray = data.getJSONArray(Constant.RESP_RING_LIST);
						initMyCircleListItemFromJSONObject(jsonArray);
					}
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		private void initMyCircleListItemFromJSONObject(JSONArray jsonArray) throws JSONException {
			Gson gson = new Gson();
			String msgNum = getString(R.string.mycircle_msgnumber);
			String fansNum = getString(R.string.mycircle_fansnumber);
			for (int i = 0; i < jsonArray.length(); i++) {
				RingEntity ringEntity = gson.fromJson(jsonArray.getJSONObject(i).toString(), RingEntity.class);
				Map<String, Object> item = new HashMap<String, Object>();
				item.put("msgNum", msgNum + ringEntity.getMsg_count());
				item.put("fansNum", fansNum + ringEntity.getRing_user_list().length);
				item.put("circleName", ringEntity.getRing_name());
				mItems.add(item);
				allRings.add(ringEntity);
			}

		}

		private void bindItemClickedEvent() {
			mListView.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					ListView listView = (ListView) parent;
					Log.v("Test", "id = " + id + "(" + listView.getItemAtPosition(position).toString() + ")");
					ringEntity = allRings.get((int) id);
					showMoreLinesInputField();
				}
			});
		}

		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			// TODO Auto-generated method stub
			if(resultCode == RESULT_OK){
				switch (requestCode) {
				case Constant.ACTIVITY_REQUESTCODE_ALBUM:
					String str = checkImagePath(data);
					if(str != null){
						takePhoto = false;
						fromAlbum = true;
						String end = str.substring(str.lastIndexOf("."));
						int endindex = str.lastIndexOf("/")+1;
						String fpath = str.substring(0, endindex);
						File file = new File(str);
						String filename = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+end;
						File newFile = new File(fpath+filename);
						file.renameTo(newFile);
						
						fromalbumPath = newFile.getAbsolutePath();
						Log.d("fromalbum", fromalbumPath);
						photoName = filename;
						Log.d("photoName", photoName);
						Log.d("ImageChoosepath", str);
					}
					startPhotoZoom(data.getData());
					break;
				case Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE:
					String status = Environment.getExternalStorageState();
					if(!status.equals(Environment.MEDIA_MOUNTED)){
						Toast.makeText(CircleSendSMSActivity.this, getString(R.string.sdcard_notin), Toast.LENGTH_LONG).show();
						return ;
					}
					Uri uri = data.getData();
					if(uri != null){
						mDrawableAvater = BitmapFactory.decodeFile(uri.getPath());
					}
					if(mDrawableAvater == null){
						Bundle bundle = data.getExtras();
						if(bundle != null){
							mDrawableAvater =  (Bitmap)bundle.get("data");
						}else{
							Toast.makeText(CircleSendSMSActivity.this, "获取照片失败", Toast.LENGTH_LONG).show();
							return;
						}
					}
					
					FileOutputStream outputStream = null;
					photoName = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+".jpg";
					String dirstr = Environment.getExternalStorageDirectory().toString() +"/glemei";
					File dir = new File(dirstr);
					
					if (!dir.exists()) {
						dir.mkdir(); 
					}
					File file = new File(dirstr, photoName);
					try {
						file.createNewFile();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					takePhotoPath = file.getAbsolutePath();
					Log.d("takePhotoPath", takePhotoPath);
					try {
						outputStream = new FileOutputStream(takePhotoPath);
						mDrawableAvater.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
						
					} catch (Exception e) {
						// TODO: handle exception
					}
					Log.d("beginWriteImage", "begin");
					WriteImage();
					takePhoto = true;
					fromAlbum = false;
					btnImageView.setBackgroundDrawable(AvatarUtil.Bitmap2Drawable(mDrawableAvater));
					
					break;
				case Constant.ACTIVITY_REQUESTCODE_NEWAVATER:
					Drawable newAvater = getNewAvater(data);
					
					if (newAvater != null) {
						mDrawableAvater = ((BitmapDrawable) newAvater).getBitmap();
						btnImageView.setCompoundDrawables(newAvater, null, null, null);
					}
					break;	
				
				default:
					break;
				}
			}
			
		}
		
		 public void WriteImage() {  
		        try {  
		            FileInputStream fis = new FileInputStream(takePhotoPath);  
		            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		            byte[] buffer = new byte[8192];  
		            int count = 0;  
		            while ((count = fis.read(buffer)) >= 0) {  
		                baos.write(buffer, 0, count);  
		  
		            }  
		            fis.close(); 
		            
		        } catch (FileNotFoundException e) {  
		            e.printStackTrace();  
		        } catch (IOException e) {  
		            e.printStackTrace();  
		        }  
		 }  
		
		 
		public void uploadFile() throws ClientProtocolException, IOException{
			File file = null;
			
			if(takePhoto){
				file = new File(takePhotoPath);
			}
			if(fromAlbum){
				file = new File(fromalbumPath);
			}
			
			 try {
//					URL url = new URL("http://192.168.3.100:8088/phpProject/push/android_upload.php?filename="+photoName);
		            URL url = new URL(Constant.URL_PARTY_COMMENT +"?filename="+photoName);
		            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
		            httpUrlConnection.setDoOutput(true);
		            httpUrlConnection.setDoInput(true);
		            httpUrlConnection.setUseCaches(false);
		            httpUrlConnection.setRequestMethod("POST");
		            OutputStream os = httpUrlConnection.getOutputStream();
		            Thread.sleep(100);
		            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));

		            int bufSize = 0;
		            byte[] buffer = new byte[1024];
		            while ((bufSize = fis.read(buffer)) != -1) {
		                os.write(buffer, 0, bufSize);
		            }
		            fis.close();

		            String responMsg = httpUrlConnection.getResponseMessage();
		            Log.d("TAG", "responMsg =====" + responMsg);
		        } catch (Exception e) {
		           e.printStackTrace();
		        }
		
		}
		
		private String checkImagePath(Intent data){
			Cursor cursor = null;
			String path = null;
			try {
				Uri originalUri = data.getData();
				path = originalUri.toString();
				String[] proj = { MediaStore.Images.Media.DATA };
				cursor = managedQuery(originalUri, proj, null, null, null);
				if (cursor != null) {
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor.moveToFirst();
					// 最后根据索引值获取图片路径
					path = cursor.getString(column_index);
					Log.d("checkImagePath_path", path);
				}
			}
		    catch (Exception e) {
				Log.e("checkImage", e.getMessage());
			} finally {
				if (cursor != null && !cursor.isClosed()) 
					cursor.close();
			}
			
			return path;		
		}
		
		public static String formatDatetime(Date date, String format) {  
	        DateFormat df = new SimpleDateFormat(format);  
	        return df.format(date);  
	    }  
		
		private Drawable getNewAvater(Intent data) {
			if (null != data) {
				Bundle bundle = data.getExtras();
				if (null != bundle) {
					Bitmap photo = bundle.getParcelable("data");
					
					Drawable drawable = new BitmapDrawable(photo);
					drawable.setBounds(0, 0, 100, 100);
					return drawable;
				}
			}
			return null;

		}
		
		public void startPhotoZoom(Uri uri) {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, "image/*");
			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 300);
			intent.putExtra("outputY", 300);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_NEWAVATER);
		}
		
		public void goBackButton_OnClick(View v) {
			NavUtils.navigateUpFromSameTask(this);
		}
	}
